<?php
namespace app\admin\controller;

use think\Validate;
use app\admin\model\AuthRule;

/**
 * 权限规则管理，仅超管有管理权限
 * Class Rule
 * @package app\admin\controller
 */
class Rule extends Base
{
    protected $model;

    public function initialize()
    {
        parent::initialize();
        $this->model = AuthRule::getInstance();
    }

    public function lists()
    {
        $where = [];
        //管理员列表
        $lists = $this->model->where($where)->select();
        $this->assign('lists', $lists);
        return $this->fetch();
    }

    /**
     * 用户组添加/修改
     */
    public function publish()
    {
        if ($this->request->isPost()) {
            $post = $this->request->param();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $validate = new Validate([
                ['title', 'require|token', '角色名称不能为空'],
            ]);
            //验证数据合法性
            if (!$validate->check($post)) {
                $this->error($validate->getError());
            }
            $id = isset($post['id']) ? intval($post['id']) : 0;
            if ($id < 1) {
                $status = $this->model->addData($post);
            } else {
                $status = $this->model->editData($post);
            }
            if ($status) {
                $this->success('操作成功', url('lists'));
            } else {
                $this->error($this->model->getError());
            }
        } else {
            $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
            $info = [];
            if ($id > 0) {
                $info = $this->model->getOne($id);
            }
            $this->assign($info);
            return $this->fetch();
        }
    }

    public function delete()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        if ($id < 1) {
            return $this->error("ID非法！");
        }
        if ($this->model->deleteData($id)) {
            return $this->success("删除成功！");
        } else {
            return $this->error($this->model->getError());
        }
    }


}